<template>
  <!-- 搜索工作栏 -->
  <div class="header competitionTeamList-yunying">
    <div class="title-box">
      <span>当前项目: </span>
      <!-- <span>深圳高等金融研究院-数据分析项目-遴选</span> -->
      <span>{{ $route.query.projectName }}</span>
    </div>

    <div class="search-tools">
      <SearchBar
        ref="formParams"
        :search-config="searchConfig"
        label-width="100px"
        label-position="right"
        style="margin: 0 0 15px 0"
        :slot-span="4"
        @transferSearchParams="transferSearchParams"
        @search="handleSearch"
        @resetSearch="resetSearch"
      >
        <el-button slot="inner" size="small" type="primary" @click="handleExport">导出</el-button>
        <!-- 按钮批量操作(发布:release,不发布:noRelease,删除:delete,更换栏目:typeIds,还原:recovery,月榜:month,周榜:week) -->
        <el-button
          v-if="searchParams.scheduleType === 1"
          :disabled="tableSelectList.length === 0"
          type="primary"
          size="small"
          @click="handleBatchOperate('in', 'batch')"
        >
          批量入选
        </el-button>
        <el-button
          v-if="searchParams.scheduleType === 1"
          :disabled="tableSelectList.length === 0"
          type="primary"
          size="small"
          @click="handleBatchOperate('out', 'batch')"
        >
          批量撤销入选
        </el-button>
      </SearchBar>
    </div>
    <Table
      ref="tableList"
      :table-config="resultClassifiyConfig"
      :table-data="tableData"
      :total="total"
      :page-no="pageNo"
      :page-size="pageSize"
      @sortChange="sortChange"
      @handleSelectionChange="handleSelectionChange"
      @handleChangePage="handleChangePage"
    >
      <el-table-column label="操作" align="center" width="430" fixed="right">
        <template slot-scope="scope">
          <div class="btn-box">
            <el-button size="mini" @click="handleView(scope.row)">查看</el-button>
            <el-button v-if="searchParams.scheduleType !== 4 && !scope.row.checkStatus" size="mini" @click="handleBatchOperate('in', 'row', scope.row)">入选</el-button>
            <el-button v-if="searchParams.scheduleType !== 4 && scope.row.checkStatus === 1" size="mini" @click="handleBatchOperate('out', 'row', scope.row)">撤销入选</el-button>
            <el-button v-if="searchParams.scheduleType === 4 && !scope.row.checkStatus" size="mini" @click="handleGiveGift(scope.row, 'give')">给予奖励</el-button>
            <el-button v-if="searchParams.scheduleType === 4 && scope.row.checkStatus === 1" size="mini" @click="handleGiveGift(scope.row, 'get')">撤销奖励</el-button>
            <el-button size="mini" @click="handleGrade(scope.row)">评分</el-button>
            <el-button v-if="scope.row.annexUrl" size="mini" type="primary" :disabled="!scope.row.annexUrl" @click="handleDown(scope.row)">下载作品</el-button>
            <el-upload
              class="upload-demo"
              :action="actionUrl"
              :headers="headers"
              :on-change="handleFileChange"
              :before-upload="handleBeforeUpload"
              :on-progress="handleFileUploadProgress"
              :on-success="handleFileSuccess"
              :on-error="handleUploadError"
              :show-file-list="false"
            >
              <el-button style="margin: 0 10px" size="mini" type="primary" @click="handleUpdate(scope.row)">上传作品</el-button>
            </el-upload>
          </div>
        </template>
      </el-table-column>
    </Table>
    <ViewNews ref="viewNews" />
    <AddDetailPop ref="addDetailPop" @success="handleSearch" />
    <ViewPerson ref="viewPerson" @success="getList" />
    <BeSelected ref="beSelected" @success="getList" />
    <GradePop ref="gradePop" @success="getList" />
    <GiveGift ref="giveGift" @success="getList" />
  </div>
</template>
<script>
import { getMsgTypeList, deleteMsg, updateType } from '@/api/inner-msg/index.js'
import { middleSearchConfig, rightFormConfig, resultClassifiyConfig } from './initData'
import SearchBar from '@/views/components/SearchBar'
import Table from '@/views/components/Table'
import ViewNews from './components/viewNews.vue'
import AddDetailPop from './components/addDetailPop.vue'
import ViewPerson from './components/viewPerson.vue'
import { getEntryInfoPageByProjectId, batchUpdateStatus, exportApi, uploadAnnex } from './api'
import BeSelected from './components/beSelected.vue'
import GradePop from './components/gradePop.vue'
import GiveGift from './components/giveGift.vue'
import { getToken } from '@/utils/auth'

export default {
  name: 'NewsList',
  components: {
    SearchBar,
    Table,
    ViewNews,
    AddDetailPop,
    ViewPerson,
    BeSelected,
    GradePop,
    GiveGift
  },
  data() {
    return {
      searchConfig: null,
      resultClassifiyConfig,
      tableData: [],
      total: 0,
      pageNo: 1,
      pageSize: 10,
      tableSelectList: [],
      sortable: null,
      searchParams: {},
      sortingFields: null,
      scheduleType: null,
      currentItem: null,
      headers: { Authorization: 'Bearer ' + getToken() }, // 设置上传的请求头部
      actionUrl: `${process.env.VUE_APP_BASE_API + (process.env.NODE_ENV === 'development' ? 'admin-api-test/' : 'admin-api/')}infra/file/upload`
    }
  },
  created() {
    this.scheduleType = Number(this.$route.query.scheduleType)
    this.projectName = this.$route.query.projectName
    const newConfig = this.scheduleType === 0 ? JSON.parse(JSON.stringify(rightFormConfig))
      : JSON.parse(JSON.stringify(middleSearchConfig))
    this.searchConfig = newConfig.map(v => {
      if (v.keyIndex === 'scheduleType') {
        return {
          ...v,
          value: this.scheduleType
        }
      } else {
        return v
      }
    })
    this.searchParams = {
      ...this.searchParams,
      scheduleType: this.scheduleType
    }
    this.getList()
  },
  mounted() {
    // this.dragSort();
  },
  methods: {
    handleUploadError() {},
    handleFileChange() {},

    handleBeforeUpload(file) {
      const fileTypeList = ['.pdf', '.zip'].map(v => {
        return v.slice(1)
      })
      let isAble = false
      fileTypeList.forEach(v => {
        if (file.type.indexOf(v) > -1) {
          isAble = true
        }
      })
      console.log(fileTypeList, file.type, '----file---')
      if (!isAble) {
        this.$modal.msgError(`请上传${this.fileType.join('/')}文件`)
        return false
      }
      return true
    },
    // 上传成功回调
    handleFileSuccess(res, file) {
      console.log(res, file, '----上传结果')
      // this.$refs.upload.clearFiles()
      // // 清理
      // this.upload.isUploading = false
      // this.$modal.closeLoading()
      // 如果上传成功
      if (res.code === 0) {
        const annexName = file.name
        const annexUrl = res.data
        uploadAnnex({
          annexName: annexName,
          annexUrl: annexUrl,
          entryId: this.currentItem.id
        }).then(res => {
          if (res && res.code === 0) {
            this.$message.success('上传成功')
          } else {
            this.$message.error('上传失败，请稍后再试')
          }
        })
      } else {
        this.$modal.msgError(res.msg)
      }
    },
    handleFileUploadProgress() {},
    resetSearch() {
      this.searchParams = {
        scheduleType: Number(this.searchParams.scheduleType)
      }
      this.sortingFields = null
      this.$refs.tableList && this.$refs.tableList.$children[0].clearSort()
      this.handleSearch()
    },
    async handleSort() {
      const { code, data } = await getMsgTypeList({
        pageNo: 1,
        pageSize: 999
      })
      if (code === 0) {
        this.$refs.dragSort && this.$refs.dragSort.open({
          list: data.list
        })
      }
    },
    transferSearchParams(params) {
      this.searchParams = {
        ...this.searchParams,
        ...params
      }
    },
    handleSearch() {
      this.pageNo = 1
      this.getList()
    },
    getParams() {
      const params = {}
      const { projectId, scheduleType } = this.$route.query
      for (const key in this.searchParams) {
        if (this.searchParams[key] || this.searchParams[key] === 0) {
          params[key] = this.searchParams[key]
        }
      }
      const allP = {
        ...params,
        projectId,
        sortField: this.sortingFields ? this.sortingFields[0] : null,
        pageNo: this.pageNo,
        pageSize: this.pageSize
      }
      return allP
    },
    async getList() {
      const params = this.getParams()
      const { code, data } = await getEntryInfoPageByProjectId(params)
      if (code === 0) {
        this.tableData = data.list.map(v => {
          return {
            ...v,
            checkStatusStr: v.checkStatus === 0 ? '未入选' : v.checkStatus === 1 ? '入选' : '',
            lookStatusStr: v.lookStatus === 1 ? '未查看' : v.lookStatus === 2 ? '已查看' : '',
            age: v.birthday ? this.getAge(v.birthday) : '--'
          }
        })
        this.total = data.total
      } else {
        this.tableData = []
        this.total = []
      }
    },

    async handleExport() {
      const params = this.getParams()
      const res = await exportApi(params)
      this.$download.excel(res, '项目列表.xls')
    },

    getAge(strBirthday) {
      let returnAge

      const strBirthdayArr = strBirthday.split('-')
      const birthYear = strBirthdayArr[0]
      const birthMonth = strBirthdayArr[1]
      const birthDay = strBirthdayArr[2]

      const d = new Date()
      const nowYear = d.getFullYear()
      const nowMonth = d.getMonth() + 1
      const nowDay = d.getDate()

      if (nowYear == birthYear) {
        returnAge = 0// 同年 则为0岁
      } else {
        var ageDiff = nowYear - birthYear // 年之差
        if (ageDiff > 0) {
          if (nowMonth == birthMonth) {
            var dayDiff = nowDay - birthDay// 日之差
            if (dayDiff < 0) {
              returnAge = ageDiff - 1
            } else {
              returnAge = ageDiff
            }
          } else {
            var monthDiff = nowMonth - birthMonth// 月之差
            if (monthDiff < 0) {
              returnAge = ageDiff - 1
            } else {
              returnAge = ageDiff
            }
          }
        } else {
          returnAge = -1// 出生日期不能大于今天
        }
      }
      return returnAge
    },

    async handleBatchOperate(tag, type, row = {}) {
      const { projectId, scheduleType } = this.$route.query
      let ableRows = []
      if (tag === 'in') {
        
        if (type === 'batch') {
          ableRows = this.tableSelectList.filter(v => this.searchParams.scheduleType !== 4 && !v.checkStatus)
          if (!ableRows || ableRows.length === 0) {
            this.$message.warning('请选择未入选比赛')
            return
          }
        }

        this.$refs.beSelected && this.$refs.beSelected.open({
          list: ableRows,
          projectId,
          rowId: row.id,
          scheduleType,
          type,
          title: this.projectName
        })
      } else {
        if (type === 'batch') {
          ableRows = this.tableSelectList.filter(v => this.searchParams.scheduleType !== 4 && v.checkStatus === 1)
          if (!ableRows || ableRows.length === 0) {
            this.$message.warning('请选择已入选比赛')
            return
          }
        }

        this.$confirm('是否确定撤销入选？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const { code } = await batchUpdateStatus({
            ids: row.id ? [row.id] : ableRows.map(v => v.id),
            type: 0
          })
          if (code !== 0) return
          this.$message.success('撤销入选成功')
          this.getList()
        })
      }
    },

    handleGiveGift(row, type) {
      console.log(row, '---row-->>>')
      if (type === 'give') {
        this.$refs.giveGift && this.$refs.giveGift.open({
          rowId: row.id,
          scheduleType: this.scheduleType,
          title: this.projectName
        })
      } else {
        this.$confirm('是否確定撤销奖励？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const { code } = await batchUpdateStatus({
            ids: [row.id],
            type: 0
          })
          if (code !== 0) return
          this.$message.success('撤销奖励成功')
          this.getList()
        })
      }
    },

    handleGrade(row) {
      this.$refs.gradePop && this.$refs.gradePop.open({ entryId: row.id })
    },
    handleUpdate(item) {
      this.currentItem = item
    },
    handleDown(row) {
      if (row.annexUrl) {
        window.open(row.annexUrl, '_blank')
      }
    },

    handleSelectionChange(val) {
      this.tableSelectList = val
    },
    handleChangePage({ pageNo, pageSize }) {
      this.pageNo = pageNo
      this.pageSize = pageSize
      this.getList()
    },
    // 新建
    handleAdd() {
      this.$refs.addDetailPop && this.$refs.addDetailPop.open({ popType: 'add' })
    },
    handleView(row) {
      const { projectId, scheduleType } = this.$route.query
      this.$refs.viewPerson && this.$refs.viewPerson.open({
        projectId,
        row,
        scheduleType: this.scheduleType,
        title: this.projectName
      })
    },
    // 不发布
    // 暂停发布
    async handleOperatePush(row, status) {
      const mark = status === '0' ? '下架' : '上架'
      this.$confirm(`是否确认${mark}?`, '提示').then(async() => {
        const { code } = await updateType({
          id: row.id,
          status
        })
        if (code !== 0) return
        this.$message.success('操作成功')
        this.getList()
      })
    },

    handleEdit(row) {
      this.$refs.addDetailPop && this.$refs.addDetailPop.open({ popType: 'edit', row: JSON.stringify(row) })
    },
    handleDelete({ id }) {
      this.$confirm('是否确认删除?', '提示').then(async() => {
        const { code, msg } = await deleteMsg({
          id
        })
        if (code !== 0) {
          this.$message.error(msg)
          return
        }
        this.$message.success('删除成功')
        this.handleSearch()
      })
    },
    confirmDelete() {
      this.$message.success('删除成功')
    },
    sortChange(sortingFields) {
      const newFields = sortingFields ? sortingFields.map(v => {
        return {
          ...v,
          field: 't.' + v.field
        }
      }) : null
      this.sortingFields = newFields
      this.handleSearch()
    }
  }
}
</script>

<style lang='scss' scoped>
    .header {
        display: flex;
        flex-direction: column;
        padding: 0 20px;

        .title-box {
          display: flex;
          justify-content: flex-start;
          margin: 10px 0;
          font-size: 16px;
        }

        .search-tools {
            display: flex;
            justify-content: space-between;
        }

        .btn-box {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            flex-flow: row wrap;
            .btns {
                color: #02A7F0;
                cursor: pointer;
                display: inline-block;
                width: 33.33%
            }
            .delete {
                color: #f56c6c;
            }
        }
    }
</style>

<style lang="scss">
  .competitionTeamList-yunying {
    .basic-table {
      .el-table__body-wrapper {
        height: calc(100vh - 287px);
      }
    }
    .basic-table::before {
      height: 0;
    }

    .pagination-container {
      padding: 0 !important;
    }
  }
</style>
